package com.zhima.service.impl;

import com.zhima.dto.AuthParamsDTO;
import com.zhima.dto.UserDTOExtension;
import com.zhima.exception.ZhimaOjException;
import com.zhima.feignclient.UserFeignClient;
import com.zhima.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import static com.zhima.exception.ErrorCode.PASSWORD_OR_USERNAME_WRONG;
import static com.zhima.exception.ErrorCode.USER_NOT_FOUND;

@Service
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override

    public UserDTOExtension auth(AuthParamsDTO authParamsDTO) {
        UserDTOExtension userDTOExtension = userFeignClient.authInfoByUserName(authParamsDTO.getUserName());
        if (userDTOExtension == null) {
            throw new ZhimaOjException(USER_NOT_FOUND);
        }
        String rightPassword = userDTOExtension.getPassword();
        String submitPassword = authParamsDTO.getPassword();
        if (!passwordEncoder.matches(submitPassword, rightPassword)) {
            throw new ZhimaOjException(PASSWORD_OR_USERNAME_WRONG);
        }
        return userDTOExtension;
    }
}
